﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.EventSystems;


public class Comidy : MonoBehaviour
{
    public int mysize;
    public int index;
    public bool isFragile = false;
    public bool isLeak = false;
    public bool isMove = false;

    Tweener dt;
    bool canDestroy = true;

    private void OnMouseDown()
    {
        if (isMove)
            dt.Kill();
        else
        {
            this.gameObject.tag = "drag";
            GameController.instance.CreateBoxAtPosition(index);
        }
    }

    LayerMask mask = 1 << 8;
    Ray clickRay;
    RaycastHit clickPoint;
    private void OnMouseDrag()
    {
        clickRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(clickRay, out clickPoint, mask))
        {
            transform.position = new Vector3(clickPoint.point.x, transform.position.y, clickPoint.point.z);
        }
    }

    private void OnMouseUp()
    {
        if (canDestroy)
            Destroy(this.gameObject);
        else
        {
            this.enabled = false;
            this.GetComponent<BoxCollider>().enabled = false;

            transform.localScale = Vector3.one;
            transform.SetParent(GameController.instance.currentBox.transform);
            transform.localPosition = Vector3.zero + Vector3.up * 0.08f + Vector3.forward * 0.1f;
            transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));

            GameController.instance.comidySize = mysize;
            GameController.instance.comidyFragile = isFragile;
            GameController.instance.comidyLeak = isLeak;

            GameController.instance.MoveBox(this.gameObject);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 9 && GameController.instance.hasBox == true)
            canDestroy = false;
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.layer == 9)
            canDestroy = true;
    }

    // Use this for initialization
    public void Init(bool isMove = false, int index = 0)
    {
        this.isMove = isMove;
        this.index = index;
        if (isMove)
        {
            Vector3[] vecPath = new Vector3[GameController.instance.path.Count];
            for (int i = 0; i < GameController.instance.path.Count; i++)
                vecPath[i] = GameController.instance.path[i].transform.position;
            dt = transform.DOPath(vecPath, 8, PathType.CatmullRom, PathMode.Full3D, 10).SetLookAt(0).SetEase(Ease.Linear);
            dt.OnComplete(() => Destroy(this.gameObject));
        }
    }
}